// pages/seal/classify/classify.js
import config from '../../../utils/config';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    sealType: null,
    seals: [], // 存储获取到的印章数据
    selectedSealId: null, // 存储选中的印章ID
    selectedMaterial: null, // 存储选中的材质
    selectedSealType: null, // 存储选中的印章类型
    material: [],
    sealTypes: null,
    previousSelections: null, // 存储上一次的选择
    price: '0.00', // 当前价格
    totalPrice: '0.00', // 总价格
    canSelectSealType: false, // 是否可以选择印章类型
    isCalculatingPrice: false, // 是否正在计算价格
    priceCalculationTimer: null, // 价格计算定时器
    companyInfo: null,
    personalInfo: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 检查是否有登录回跳缓存
    const redirectCache = wx.getStorageSync('redirectAfterLogin');
    if (redirectCache && redirectCache.sealForm) {
      this.setData({
        ...redirectCache.sealForm
      });
      wx.removeStorageSync('redirectAfterLogin');
    }
    // 接收sealType参数
    if (options.sealType) {
      this.setData({
        sealType: options.sealType
      });
      // 读取缓存并回显
      const cache = wx.getStorageSync('sealFormCache') || {};
      if (cache[options.sealType]) {
        // 回显缓存数据
        this.setData({
          ...cache[options.sealType]
        });
      }
      console.log('接收到的印章类型ID:', options.sealType);
      
      // 获取 material 数据（电子印章无需材质，跳过）
      if (options.sealType !== '4') {
        this.getSealMaterial();
      } else {
        // 电子印章可直接选择印章类型
        this.setData({
          canSelectSealType: true
        });
      }
      // 根据sealType获取印章数据
      this.getSealsByType(options.sealType);
    }

    // 如果有上一次的选择，恢复数据
    if (options.previousSelections) {
      try {
        const previousSelections = JSON.parse(options.previousSelections);
        this.setData({
          previousSelections: previousSelections,
          material: this.data.material.map(item => ({
            ...item,
            checked: previousSelections.material === item.value
          })),
          sealTypes: this.data.sealTypes.map(item => ({
            ...item,
            checked: previousSelections.sealTypes.includes(item.value)
          }))
        });
      } catch (e) {
        console.error('解析上一次选择数据失败:', e);
      }
    }

    // 获取全局数据
    const app = getApp();
    this.setData({
      companyInfo: app.globalData.companyInfo,
      personalInfo: app.globalData.personalInfo
    });
  },

  /**
   * 获取印章材质
   */
  getSealMaterial: function() {
    wx.request({
      url: `${config.baseUrl}/seal/getMaterial`,
      method: 'GET',
      success: (res) => {
        console.log(res);
        if (res.data && res.data.code === 200 && res.data.data) {
          // 填补material
          const materialData = res.data.data;
          const formattedMaterial = Object.entries(materialData).map(([value, name]) => ({
            value,
            name
          }));
          
          this.setData({
            material: formattedMaterial
          });
        } else {
          wx.showToast({
            title: '获取印章材质失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('获取印章材质失败:', err);
      }
    });
  },

  /**
   * 根据印章类型获取印章数据
   */
  getSealsByType: function(sealType) {
    wx.request({
      url: `${config.baseUrl}/seal/getClassify/${sealType}`,
      method: 'GET',
      success: (res) => {
        console.log(res);
        if (res.data && res.data.code === 200 && res.data.data) {
          // 填补sealTypes
          const formattedSealTypes = res.data.data.map(item => ({
            value: item.id.toString(),
            name: item.name,
            discount: item.discount === 1
          }));
          
          this.setData({
            sealTypes: formattedSealTypes
          });
        } else {
          wx.showToast({
            title: '获取印章分类失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('获取印章分类失败:', err);
      }
    });
  },

  /**
   * 选择印章
   */
  selectSeal: function(e) {
    const sealId = e.currentTarget.dataset.id;
    console.log('选择的印章ID:', sealId);
    
    // 更新选中状态
    this.setData({
      selectedSealId: sealId
    });
  },
  
  /**
   * 选择材质
   */
  materialChange: function(e) {
    const materialValue = e.detail.value;
    console.log('选择的材质:', materialValue);
    
    this.setData({
      selectedMaterial: materialValue,
      material: this.data.material.map(item => ({
        ...item,
        checked: item.value === materialValue
      })),
      canSelectSealType: true
    }, () => {
      this.saveToCache();
    });
    
    // 计算价格
    this.calculatePrice();
  },
  
  /**
   * 选择印章类型（支持多选）
   */
  selectSealType: function(e) {
    // 检查是否已选择材质（电子印章无需材质）
    if (!this.data.canSelectSealType) {
      wx.showToast({
        title: '请先选择材质',
        icon: 'none',
        duration: 2000
      });
      return;
    }

    const type = e.currentTarget.dataset.type;
    const sealTypes = this.data.sealTypes.map(item => {
      if (item.value === type) {
        return { ...item, checked: !item.checked };
      }
      return item;
    });
    
    this.setData({
      sealTypes: sealTypes
    }, () => {
      this.saveToCache();
    });
    
    // 获取所有选中的印章类型
    const selectedTypes = sealTypes
      .filter(item => item.checked)
      .map(item => item.value);
    
    console.log('选中的印章类型:', selectedTypes);
    
    // 计算价格
    this.calculatePrice();
  },
  
  /**
   * 计算价格
   */
  calculatePrice: function() {
    // 清除之前的定时器
    if (this.data.priceCalculationTimer) {
      clearTimeout(this.data.priceCalculationTimer);
    }

    // 设置正在计算状态
    this.setData({
      isCalculatingPrice: true
    });

    // 设置2秒后调用接口
    const timer = setTimeout(() => {
      this.callPriceCalculationAPI();
    }, 1000);

    this.setData({
      priceCalculationTimer: timer
    });
  },

  /**
   * 调用价格计算接口
   */
  callPriceCalculationAPI: function() {
    // 获取选中的材质和印章类型
    const selectedMaterial = this.data.sealType === '4' ? null : this.data.material.find(item => item.checked);
    const selectedTypes = this.data.sealTypes
      ? this.data.sealTypes.filter(item => item.checked).map(item => item.value)
      : [];

    if ((this.data.sealType !== '4' && !selectedMaterial) || selectedTypes.length === 0) {
      this.setData({
        price: '0.00',
        totalPrice: '0.00',
        isCalculatingPrice: false
      });
      return;
    }

    // 调用后端接口计算价格
    wx.request({
      url: `${config.baseUrl}/seal/calculatePrice`,
      method: 'POST',
      header: {
        Authorization : wx.getStorageSync('token')
      },
      data: {
        // 电子印章不传材质
        ...(this.data.sealType !== '4' ? { sealMaterialId: selectedMaterial.value } : {}),
        sealClassifyIds: selectedTypes
      },
      success: (res) => {
        if (res.data && res.data.code === 200) {
          this.setData({
            price: res.data.data.price.toFixed(2),
            totalPrice: res.data.data.totalPrice.toFixed(2),
            isCalculatingPrice: false
          });
        } else {
          wx.showToast({
            title: '价格计算失败',
            icon: 'none'
          });
          this.setData({
            isCalculatingPrice: false
          });
        }
      },
      fail: (err) => {
        console.error('价格计算失败:', err);
        wx.showToast({
          title: '价格计算失败',
          icon: 'none'
        });
        this.setData({
          isCalculatingPrice: false
        });
      }
    });
  },

  /**
   * 点击价格重新计算
   */
  recalculatePrice: function() {
    this.calculatePrice();
  },

  /**
   * 确认选择
   */
  confirmSelection: function() {
    // 新增：判断价格是否正在计算
    if (this.data.isCalculatingPrice) {
      wx.showToast({
        title: '还在计算价格，请稍后再试',
        icon: 'none'
      });
      return;
    }
    // 用户点击确定选择时也缓存一次
    this.saveToCache();
    // 检查登录状态
    const token = wx.getStorageSync('token');
    if (!token) {
      // 缓存当前页面路径和表单数据
      const pages = getCurrentPages();
      const currentPage = pages[pages.length - 1];
      // 拼接参数
      let url = '/' + currentPage.route;
      if (currentPage.options && Object.keys(currentPage.options).length > 0) {
        const params = Object.entries(currentPage.options).map(([k, v]) => `${k}=${encodeURIComponent(v)}`).join('&');
        url += '?' + params;
      }
      // 缓存表单数据
      wx.setStorageSync('redirectAfterLogin', {
        url,
        sealForm: {
          material: this.data.material,
          sealTypes: this.data.sealTypes,
          selectedMaterial: this.data.selectedMaterial,
          selectedSealType: this.data.selectedSealType,
          price: this.data.price,
          totalPrice: this.data.totalPrice
        }
      });
      wx.navigateTo({
        url: '/pages/login/login?redirect=1'
      });
      return;
    }

    // 获取选中的材质（电子印章无需材质）
    const selectedMaterial = this.data.sealType === '4' ? null : this.data.material.find(item => item.checked);
    // 获取选中的印章类型
    const selectedTypes = this.data.sealTypes
      ? this.data.sealTypes.filter(item => item.checked).map(item => item.value)
      : [];

    console.log('选中的材质:', selectedMaterial);
    console.log('选中的印章类型:', selectedTypes);

    if (this.data.sealType !== '4' && !selectedMaterial) {
      wx.showToast({
        title: '请选择材质',
        icon: 'none'
      });
      return;
    }

    if (selectedTypes.length === 0) {
      wx.showToast({
        title: '请选择印章类型',
        icon: 'none'
      });
      return;
    }

    // 检查是否需要校验公司/个体户信息
    if (this.data.sealType === '1' && !this.data.companyInfo) {
      wx.showToast({
        title: '请先填写公司信息',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateTo({
          url: '/pages/seal/company/company'
        });
      }, 1500);
      return;
    }
    if (this.data.sealType === '2' && !this.data.personalInfo) {
      wx.showToast({
        title: '请先填写个体户信息',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateTo({
          url: '/pages/seal/personal/personal'
        });
      }, 1500);
      return;
    }

    // 准备订单数据
    const orderData = {
      // 电子印章不传材质
      ...(this.data.sealType !== '4' ? { sealMaterialId: selectedMaterial.value } : {}),
      sealClassifyIds: selectedTypes,
      totalPrice: this.data.totalPrice
    };

    // 根据印章类型添加公司/个体户信息
    if (this.data.sealType === '1') { // 公司
      Object.assign(orderData, this.data.companyInfo);
    } else if (this.data.sealType === '2') { // 个体户
      Object.assign(orderData, this.data.personalInfo);
    }

    // 调用创建订单接口
    wx.showLoading({
      title: '正在创建订单...'
    });

    wx.request({
      url: `${config.baseUrl}/seal/createOrder`,
      method: 'POST',
      header: {
        'Authorization': token
      },
      data: orderData,
      success: (res) => {
        wx.hideLoading();
        if (res.data && res.data.code === 200) {
          // 创建订单成功，跳转到订单详情页
          wx.navigateTo({
            url: `/pages/seal/order/order?orderId=${res.data.data.orderId}&price=${this.data.price}`
          });
        } else {
          wx.showToast({
            title: res.data.message || '创建订单失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('创建订单失败:', err);
        wx.showToast({
          title: '创建订单失败，请重试',
          icon: 'none'
        });
      }
    });
  },

  /**
   * 返回上一步
   */
  goBack: function() {
    // 保存当前选择
    const currentSelections = {
      material: this.data.material.find(item => item.checked)?.value,
      sealTypes: this.data.sealTypes
        .filter(item => item.checked)
        .map(item => item.value)
    };

    // 返回上一页，并传递选择数据
    wx.navigateBack({
      delta: 1,
      success: () => {
        // 通过事件通道传递数据
        const eventChannel = this.getOpenerEventChannel();
        eventChannel.emit('updateSelections', currentSelections);
      }
    });
  },

  /**
   * 缓存当前表单数据到sealType下
   */
  saveToCache() {
    const { sealType, material, sealTypes, selectedMaterial, selectedSealType, price, totalPrice } = this.data;
    let cache = wx.getStorageSync('sealFormCache') || {};
    cache[sealType] = {
      material,
      sealTypes,
      selectedMaterial,
      selectedSealType,
      price,
      totalPrice
    };
    wx.setStorageSync('sealFormCache', cache);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})